package cn.ronghuanet.gift.exception.handler;

import cn.ronghuanet.gift.exception.BusinessException;
import cn.ronghuanet.gift.exception.code.ErrorCode;
import cn.ronghuanet.gift.util.AjaxResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

//统一异常处理
@RestControllerAdvice //Controller的通知
public class UnifyExceptionHandler {

    //已知异常
    @ExceptionHandler(BusinessException.class)
    public AjaxResult businessExceptionHandler(BusinessException e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage(e.getMessage()).setCode(e.getCode());
    }


    //jsr303校验异常出来
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
        e.printStackTrace();
        BindingResult result = e.getBindingResult();
        //获取所有的字段错误
        List<FieldError> fieldErrors = result.getFieldErrors();

        //拼接多个字段错误，每个错误用逗号分隔
        StringBuilder sb =new StringBuilder();
        fieldErrors.forEach(fieldError -> {
            String message = fieldError.getDefaultMessage();
            sb.append(message+",");
        });

        //去除最后一个逗号
        String message = sb.substring(0, sb.length() - 2);
        return AjaxResult.me().setSuccess(false).setMessage(message).setCode(ErrorCode
                .ERROR_CODE_400.getCode());
    }

    //未知异常
    @ExceptionHandler(Exception.class)
    public AjaxResult exceptionHandler(Exception e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false)
                .setMessage(ErrorCode.ERROR_CODE_500.getMessage())
                .setCode(ErrorCode.ERROR_CODE_500.getCode());
    }
}
